import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/book',
    name: 'Book',
    component: () => import(/* webpackChunkName: "book" */ '@/views/Book/Index.vue'),
    // redirect: "/book/classify",
    children: [
      {
        path: 'home',
        component: () => import(/* webpackChunkName: "book" */ '@/views/Book/Pages/HomeIndex.vue'),
      },
      {
        path: 'classify',
        component: () => import(/* webpackChunkName: "book" */ '@/views/Book/Pages/Classify.vue'),
        meta: { // 导航元信息
          auth: true // 授权字段-是否需要登陆授权
        }
      },
      {
        path: 'rack',
        component: () => import(/* webpackChunkName: "book" */ '@/views/Book/Pages/BookRack.vue'),
      },
      {
        path: 'top',
        component: () => import(/* webpackChunkName: "book" */ '@/views/Book/Pages/Top.vue'),
      }
    ]
  },
  {
    path: '/admin',
    name: 'admin',
    component: () => import(/* webpackChunkName: "book" */ '@/views/Admin/index.vue'),
    // children: [
    //   {
    //     path: '/'
    //   }
    // ]
  },
  {
    path: '/login',
    name: 'login',
    component: () => import(/* webpackChunkName: "book" */ '@/views/Admin/login.vue'),
  }
]

const router = new VueRouter({
  // mode: 'history',
  base: process.env.BASE_URL,
  routes
})


router.beforeEach((to, from, next) => {
  // 1. 路由拦截 判断是否有需要登陆授权的字段
  console.log(to)
  if (to.meta.auth) { // 说明用户在进入这个路由的时候需要先登陆
    // 2. 根据先前登陆存储的token去判断 如果有token，就说登陆了，反之
    if (sessionStorage.token) {
      next()
    } else {
      next({
        path: '/login',
        query: { fullPath: to.path } // 我在跳转到登陆的页面的时候，我把我原来的路由信息到过去，等登陆之后，再跳回到原先用户想进入的路由
      })
    }
  } else {
    next()
  }
})

export default router
